package com.example.demo.service.iml;

import com.example.demo.config.IotApiConfig;
import com.example.demo.model.common.*;
import com.example.demo.model.entity.CardDetail;
import com.example.demo.model.entity.CardInfo;
import com.example.demo.model.entity.CardPackage;
import com.example.demo.service.IotCardService;
import com.example.demo.util.SignUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Map;

import static com.example.demo.util.SignUtils.generateSign;

/**
 * 物联卡连接管理服务实现类
 */
@Service
@Slf4j
public class IotCardServiceImpl implements IotCardService {

    @Autowired
    private IotApiConfig config;

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 批量查询卡基础信息
     * @param iccids SIM卡ICCID列表
     * @return 卡基础信息列表
     */
    @Override
    public List<CardInfo> queryCardInfoList(List<String> iccids) {
        String url = buildUrl("/route/open/queryCardInfoList");
        CommonRequest<Map<String, List<String>>> request = buildRequest(Map.of("iccid", iccids));

        CommonResponse<List<CardInfo>> response = executeRequest(url, request,
                new ParameterizedTypeReference<CommonResponse<List<CardInfo>>>() {});

        return response.getResult().getData();
    }

    /**
     * 批量查询卡详情
     * @param iccids SIM卡ICCID列表
     * @return 卡详情信息列表
     */
    @Override
    public List<CardDetail> queryCardDetail(List<String> iccids) {
        String url = buildUrl("/route/open/queryCardDetail");
        CommonRequest<Map<String, List<String>>> request = buildRequest(Map.of("iccid", iccids));

        CommonResponse<List<CardDetail>> response = executeRequest(url, request,
                new ParameterizedTypeReference<CommonResponse<List<CardDetail>>>() {});

        return response.getResult().getData();
    }

    /**
     * 批量查询卡套餐
     * @param iccids SIM卡ICCID列表
     * @return 卡套餐信息列表
     */
    @Override
    public List<CardPackage> queryCardPackage(List<String> iccids) {
        String url = buildUrl("/route/open/queryCardPackage");
        CommonRequest<Map<String, List<String>>> request = buildRequest(Map.of("iccid", iccids));

        CommonResponse<List<CardPackage>> response = executeRequest(url, request,
                new ParameterizedTypeReference<CommonResponse<List<CardPackage>>>() {});

        return response.getResult().getData();
    }

    /**
     * 批量续费
     * @param renewalRequest 续费请求参数
     * @return 续费响应结果
     */
    @Override
    public RenewalResponse mulCardRenewal(RenewalRequest renewalRequest) {
        // 检查卡片数量限制
        if (renewalRequest.getIccid() != null && renewalRequest.getIccid().size() > 150) {
            throw new IllegalArgumentException("批量续费卡数量单次不能超过150张");
        }

        String url = buildUrl("/route/open/mulCardRenewal");
        CommonRequest<RenewalRequest> request = buildRequest(renewalRequest);

        CommonResponse<RenewalResponse> response = executeRequest(url, request,
                new ParameterizedTypeReference<CommonResponse<RenewalResponse>>() {});

        RenewalResponse result = response.getResult().getData();

        // 添加提示信息日志
        log.info("批量续费请求成功，请在30分钟内完成付款，renewalId: {}", result.getRenewalId());

        return result;
    }

    /**
     * 构建请求URL
     * @param path 接口路径
     * @return 完整的请求URL
     */
    private String buildUrl(String path) {
        return "http://" + config.getDomain() + path;
    }

    /**
     * 构建通用请求对象
     * @param param 业务参数
     * @return 封装后的请求对象
     */
    private <T> CommonRequest<T> buildRequest(T param) {
        CommonRequest<T> request = new CommonRequest<>();
        request.setParam(param);

        CommonRequest.VerifyInfo verify = new CommonRequest.VerifyInfo();
        verify.setAppId(config.getAppId());
        verify.setPassword(config.getPassword());
        verify.setTimeStamp(String.valueOf(System.currentTimeMillis()));
        verify.setAccessKey(config.getAccessKey());
        String sign = SignUtils.generateSign(verify);
        verify.setSign(sign);

        // 添加签名日志
        log.info("生成签名信息 - 应用ID: {}, 时间戳: {}, 签名值: {}",
                verify.getAppId(), verify.getTimeStamp(), sign);

        request.setVerify(verify);
        return request;
    }

    /**
     * 执行HTTP请求
     * @param url 请求URL
     * @param request 请求对象
     * @param responseType 响应类型
     * @return 响应结果
     */
    private <T> CommonResponse<T> executeRequest(String url, CommonRequest<?> request,
                                                 ParameterizedTypeReference<CommonResponse<T>> responseType) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        // 添加必要的头信息
        headers.set("appId", request.getVerify().getAppId());
        headers.set("password", request.getVerify().getPassword());
        headers.set("access_key", request.getVerify().getAccessKey());
        headers.set("timeStamp", request.getVerify().getTimeStamp());
        headers.set("sign", request.getVerify().getSign());

        // 构造请求体
        Map<String, Object> requestBody = Map.of(
                "Param", request.getParam(),
                "verify", request.getVerify()
        );

        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);

        try {
            // 打印请求信息用于调试
            log.info("=== 请求详情 ===");
            log.info("请求地址: {}", url);
            log.info("请求头: {}", headers);
            log.info("请求体: {}", requestBody);

            ResponseEntity<CommonResponse<T>> responseEntity =
                    restTemplate.exchange(url, HttpMethod.POST, entity, responseType);

            // 添加响应日志
            log.info("=== 响应详情 ===");
            log.info("响应状态码: {}", responseEntity.getStatusCode());
            log.info("响应头: {}", responseEntity.getHeaders());
            log.info("响应体: {}", responseEntity.getBody());

            // 添加原生响应数据日志
            log.info("=== 原生响应数据 ===");
            ResponseEntity<String> rawResponse = restTemplate.exchange(
                    url, HttpMethod.POST, entity, String.class);
            log.info("原始响应数据: {}", rawResponse.getBody());

            CommonResponse<T> response = responseEntity.getBody();
            if (!"1".equals(response.getStatus())) {
                log.error("接口返回错误状态 - 状态码: {}, 错误信息: {}",
                        response.getStatus(), response.getMessage());
                throw new RuntimeException(response.getMessage());
            }

            return response;
        } catch (Exception e) {
            log.error("请求失败，URL: " + url, e);
            log.error("请求详情 - 请求头: {}, 请求体: {}", headers, requestBody);
            throw e;
        }
    }

    /**
     * 查询续费审核状态
     * @param renewalId 批量续费请求的id
     * @return 续费状态响应
     */
    @Override
    public RenewalStatusResponse queryRenewalStatus(String renewalId) {
        String url = buildUrl("/route/open/queryRenewalStatus");
        CommonRequest<Map<String, String>> request = buildRequest(Map.of("renewalId", renewalId));

        CommonResponse<RenewalStatusResponse> response = executeRequest(url, request,
                new ParameterizedTypeReference<CommonResponse<RenewalStatusResponse>>() {});

        return response.getResult().getData();
    }
}